import * as sqlite3 from 'sqlite3';
import { Singleton } from '../common/Singleton';
const sqlite = sqlite3.verbose();

export class Database extends Singleton {
    private _db: sqlite3.Database | null = null;
    public async initDB(): Promise<Database> {
        return new Promise<Database>((resolve, reject) => {
            this._db = new sqlite.Database('./server.db', (err) => {
                if (err) {
                    console.log('数据库初始化失败', err);
                    reject(err);
                }
                else
                    resolve(this);
            });
        });
    }
    public async run(query: string, params?: any[]): Promise<void> {
        return new Promise((resolve, reject) => {
            this._db!.run(query, params, (err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        });
    }

    public async all(query: string, params?: any[]): Promise<any[]> {
        return new Promise((resolve, reject) => {
            this._db!.all(query, params, (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(rows);
                }
            });
        });
    }

    public close(): void {
        this._db!.close((err) => {
            if (err) {
                console.error('Error closing database:', err.message);
                return;
            }
            console.log('Database connection closed.');
        });
    }
}

export const db = Database.getInstance<Database>();